<template>
	<div id="divmain">
		<!--签到-->
		<div style="width:100%;">
			<div style="width:100%;text-align:center;vertical-align:middle;">
				<div >
					<div class="circle circle-active">
						<a class="btns radius5 darkcolor" style="line-height:6.25rem;font-weight:bold;font-size:160%;"
							@click="createSign" id="btnSign" ref="btnSign">签到</a>
					</div>
				</div>
				<div style="padding:5px 0 10px 0;">
					<span style="color:white;" ref="spSignLastDayText" id="spSignLastDayText">已经连续签到 <strong
							id="spSignDays" ref="spSignDays">{{dataObjs.signLastDays}}</strong> 天</span>
				</div>
			</div>
		</div>

		<!--签到日历-->
		<div>
			<div class="sign-cand">
				<div>
					<table style="width:100%;">
						<tbody>
							<tr>
								<td style="text-align:left;"><span class="darkcolor" id="spCurrentDay"
										ref="spCurrentDay">{{dataObjs.current}}</span></td>
								<td style="text-align:right;">
									<a class="btns radius5 darkbcolor" id="btnHistory" ref="btnHistory"
										style="color:white;font-size:120%;margin-right:10px;">我的签到</a>
								</td>
							</tr>
						</tbody>
					</table>
				</div>

				<div style="width:100%;">
					<table id="tblSign" ref="tblSign" class="radius5" style="width:100%;" border="0">
						<thead>
							<tr class="darkcolor trh" style="background-color:#FFF7EE;">
								<th id="th0">周日</th>
								<th>周一</th>
								<th>周二</th>
								<th>周三</th>
								<th>周四</th>
								<th>周五</th>
								<th>周六</th>
							</tr>
						</thead>
						<tbody id="signTable" ref="signTable">
							<tr class="darkcolor trb">
								<td>
									<div>1</div>
								</td>
								<td>
									<div><span>2</span></div>
								</td>
								<td>
									<div><span>3</span></div>
								</td>
								<td>
									<div>
										<span>4</span>
										<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
											class="sign_pin svg-triangle ">
											<polygon points="0,0 35,0 0,35" />
										</svg>
									</div>
								</td>
								<td>
									<div><span>5</span></div>
								</td>
								<td>
									<div><span>6</span></div>
								</td>
								<td>
									<div><span>7</span></div>
								</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>
		</div>

		<!--签到历史-->
		<div id="divHistory" ref="divHistory" class="sign-layer">
			<div class="sign-history-body">
				<div class="radius sign-history-bodymain">
					<a id="btnPopClose" ref="btnPopClose" class="smallClose">&times;</a>
					<ul class="sign-history-head clear">
						<li>
							<p>本月连续签到</p>
							<h4 id="spLastMonthSign" ref="spLastMonthSign">{{dataObjs.continuMonthSign}}</h4>
						</li>
						<li>
							<p>本月签到</p>
							<h4 id="spMonthSign" ref="spMonthSign">{{dataObjs.monthSign}}</h4>
						</li>
						<li>
							<p>总共签到数</p>
							<h4 id="spTotalSign" ref="spTotalSign">{{dataObjs.totalSign}}</h4>
						</li>
					</ul>
					<div class="sign-history-table">
						<table>
							<thead>
								<tr>
									<th>签到日期</th>
									<th>奖励</th>
									<th>详细描述</th>
								</tr>
							</thead>
							<tbody id="tblHis" ref="tblHis">
								<tr>
									<td>2021-04-14</td>
									<td>10</td>
									<td>连续签到19天額外奖励积分</td>
								</tr>
								<tr>
									<td>2021-05-10</td>
									<td>满100减3</td>
									<td>连续签到30天額外奖励充值优惠券</td>
								</tr>
							</tbody>
						</table>
					</div>
				</div>
			</div>
		</div>

	</div>
</template>

<script>
	import $ from 'jquery';
	import constant from '@/utils/constant.js' //引入
	import {
		formatUrlParams
	} from '@/utils/utils.js' //引入
	import {
		getwxUserAuthroize,
		createSign
	} from '@/apis/wx/weixinJs.js'
	import {
		getToken,
	} from '@/utils/auth'
	import moment from 'moment'
	import uwLoadJs from '@/utils/uwLoad.js'
	import apis from '@/utils/apis.js'
	export default {
		data() {
			return {
				dataObjs: {}, //签到数据
				wxUser: {}, //用户信息
			}
		},
		created() {
			//请求授权
			debugger
			try {
				let token = localStorage.getItem(constant.WX_TOKEN);
				if (token) {
					this.wxUser = JSON.parse(localStorage.getItem(token)).userInfo.wxUser;
					let openid = this.wxUser.openid;
					if (openid) {
						//授权过了，也登陆过了
						//查询用户签到数据
						//初始化基本数据结构
						let da = this.buildData();
						this.dataObjs = da;
					} else {
						//未授权，请求授权
						let urlparam = formatUrlParams();
						let code = null
						if (urlparam && urlparam['code']) {
							code = urlparam['code'];
							//授权后微信回调回来的,请求后台获取用户信息，并保存用户授权信息到用户表
							//授权后跳过来的,根据code获取用户信息,填充数据库数据，更新页面缓存用户信息
							let params = {
								code: code,
								account: this.wxUser.wxAccount
							}
							let res = uwLoadJs.ajaxRequest(params, apis.getOauth2UserInfo);
							if (res.resultCode == constant.SUCCESS && res.data && res.data != null) {
								let data = res.data;
								localStorage.clear();
								localStorage.setItem(constant.WX_TOKEN, token)
								localStorage.setItem(token, JSON.stringify(data))
								localStorage.setItem('wx_userInfo',JSON.stringify(data.userInfo) )
							}
						} else {
							getwxUserAuthroize(this);
						}
					}
				} else {
					this.$router.push({
						name: 'wxLogin',
						params: {
							url: this.$router.history.current.fullPath
						}
					})

				}
			} catch (err) {
				console.log("err" + err);
				console.log("获取用户是否授权过异常")
			}
		},
		mounted() {
			this.$showLoading({
				showLoadingToastFlag: true
			})
			this.initControls(this.dataObjs);
			//获取历史签到数据，赋值页面数据
			this.getSignHistory();
			//渲染
			this.renderData(this.dataObjs);
			//通过接口获取历史签到奖励数据，合并再重新渲染
			this.getData();
			this.$hideLoading();
		},
		methods: {
			getSignHistory() {
				let param = {
					date: this.$moment(new Date()).format("YYYY-MM"),
					account: this.wxUser.wxAccount
				}
				let res = uwLoadJs.ajaxRequest(param, apis.getSignHistory);
				if (res.resultCode == constant.SUCCESS && res.data) {
					let data = res.data;
					this.dataObjs['monthSign'] = data.monthSign;
					this.dataObjs['continuMonthSign'] = data.continuMonthSign;
					this.dataObjs['signLastDays'] = data.signLastDays;
					this.dataObjs['totalSign'] = data.totalSign;
					this.dataObjs['signDays'] = data.signDays;
					//当天是否已签到
					this.dataObjs['isSigned'] = data.isSigned;
					if(data.isSigned == true) {
						this.changeBtnSignStatus();
					}
				}

			},
			//改变签到按钮状态
			changeBtnSignStatus(){
				var btn = $("#btnSign");
				btn.attr('disabled', true).css("pointer-events","none");  ;
				btn.removeClass('actived');
				btn.text('已签到');
				$(".circle-active").removeClass("circle-active");
			},	
			//签到
			createSign() {
				if (this.dataObjs && this.dataObjs.isSigned == true) {
					return
				}
				this.$showLoading({
					showLoadingToastFlag: true
				})
				this.dataObjs.isSigned = true;
				let param = this.dataObjs;
				param["openid"] = this.wxUser.openid;
				param["account"] = this.wxUser.wxAccount;
				param['yestodayTime'] = this.$moment().subtract(1, 'days').format("YYYY-MM-DD")
				createSign(apis.createSign, param).then(res => {
					if (res.resultCode == constant.SUCCESS && res.data) {
						this.dataObjs = res.data;
						let signDays = this.dataObjs.signDays;
						//設置簽到標記
						for (var i in this.dataObjs.dates){
							let oneDay = this.dataObjs.dates[i];
							if (oneDay && oneDay != undefined) {
								for (var j in signDays) {
									if (oneDay['num'] == signDays[j]) {
										oneDay['isSigned'] = true;
									}
								}
							}
						}
						this.renderData(this.dataObjs);
						this.changeBtnSignStatus();
					}
					this.$hideLoading()
				}).catch(err => {
					console.log(err)
					this.$hideLoading()
				})
			},
			//控件
			initControls(da) {
				$('#spCurrentDay').text(da.current);
				//$('td').height($('#th0').width());

				$("#btnHistory").on('click', function() {
					$('#divHistory').fadeIn();
					this.getSumData();
				})
				$("#btnPopClose").on('click', function() {
					$('#divHistory').fadeOut();
				});
			},

			//生成初始化数据
			buildData() {
				var da = {
					dates: [], //日期数据，从1号开始
					current: '', //当前日期
					monthFirst: 1, //获取当月的1日等于星期几
					month: 0, //当前月份
					days: 0, //当前月份共有多少天
					day: 0, //今天几号了
					isSigned: false, //今天是否已经签到
					hasSumData: false, //已经有汇总数据了？
					monthSign: 0, //本月签到数量
					continuMonthSign: 0, //本月连续签到
					signLastDays: 0, //连续签到日子
					totalSign: 0, //总共签到数量
					sumDetail: [], //签到详情
					signDays: [], //签到的日期，数字
				};
				var ds = [];
				//初始化日期数据
				var dt = new Date();
				da.current = dt.getFullYear() + '年' + (dt.getMonth() + 1) + '月' + dt.getDate() +
					'日'; //dt.ToString('yyyy年M月d日');
				da.monthFirst = new Date(dt.getFullYear(), dt.getMonth(), 1).getDay();
				da.month = dt.getMonth() + 1;
				da.days = new Date(dt.getFullYear(), parseInt(da.month), 0).getDate(); //获取当前月的天数
				da.day = dt.getDate();

				for (var i = 1; i < da.days + 1; i++) {
					var o = {
						isSigned: false, //是否签到了
						num: i, //日期
						isToday: i == da.day, //是否今天
						isPass: i < da.day, //时间已过去
					};
					ds[i] = o;
				}
				da.dates = ds;
				return da;
			},

			//渲染数据
			renderData(da) {
				var root = document.getElementById("signTable");
				root.innerHTML = '';

				var tr, td;
				var st = da.monthFirst;
				var dates = da.dates;

				var rowcount = 0;
				//最多6行
				for (var i = 0; i < 42; i++) {
					if (i % 7 == 0) {
						//如果没有日期了，中断
						if (i > (st + da.days))
							break;

						tr = document.createElement('tr');
						tr.className = 'darkcolor trb';
						root.appendChild(tr);
						rowcount++;
					}
					//前面或后面的空白
					if (i < st || !dates[i - st + 1]) {
						td = document.createElement('td');
						td.innerHTML = '<div class="sign-blank"><span></span></div>';
						tr.appendChild(td);
						continue;
					}
					//填充数字部分
					var d = dates[i - st + 1];
					td = document.createElement('td');
					var tdcss = '';
					if (d.isToday)
						tdcss = 'sign-today';
					else if (d.isPass)
						tdcss = 'sign-pass';
					else
						tdcss = 'sign-future';

					if (d.isSigned) {
						tdcss = 'sign-signed ' + tdcss;
						td.innerHTML = '<div class="' + tdcss + '"><span>' + d.num +
							'</span><svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="sign-pin svg-triangle "><polygon points="0,0 35,0 0,35" /></svg></div>';
					} else {
						tdcss = 'sign-unsign ' + tdcss;
						td.innerHTML = '<div class="' + tdcss + '"><span>' + d.num + '</span></div>';
					}
					tr.appendChild(td);
				}
				//计算是否需要添加最后一行
				if ((st + da.days + 1) / 7 > rowcount)
					root.appendChild(tr);
			},

			//从服务器获取数据
			getData() {
				let d = {
					IsSigned: false,
					SignDays: []
				};
				d.SignDays = this.dataObjs.signDays;
				//是否已经签到，签到日期

				var da = this.dataObjs;
				if (!da) return;
				da.isSigned = d.IsSigned;
				for (var i = 1; i <= da.days; i++) {
					var dx = da.dates[i];
					dx.isSigned = d.SignDays.indexOf(dx.num) >= 0;
				}
				this.renderData(da);
			},

			//获取汇总数据
			getSumData() {
				var da = this.dataObjs;
				if (!da || da.hasSumData) return;

				//WH.getAjax(baseUrl + 'MonthSummary').done(function (d) {
				//    if (!d.IsSuccess) {
				//        Msg.notifyWarn(d.ResultMessage);
				//        return;
				//    }
				//    var res = d.Result;
				//    if (!res)
				//        return;
				//    //var res = {
				//    //    "LastCount": 1,
				//    //    "MonthLastCount": 1,
				//    //    "MonthCount": 1,
				//    //    "TotalCount": 1,
				//    //    "Detail": [
				//    //        {
				//    //            "SignTime": "2018-10-10 14:05:53",
				//    //            "IP": "::1",
				//    //            "Platform": "WinNT",
				//    //            "Device": null
				//    //        }
				//    //    ]
				//    //}

				//    da.hasSumData = true;
				//    da.monthSign = res.MonthCount;
				//    da.signLastDays = res.MonthLastCount;
				//    da.totalSign = res.TotalCount;
				//    da.sumDetail = res.Detail;

				//    renderSumData(da);

				//}).fail(ajaxError);
			},

			//渲染汇总数据
			renderSumData(da) {
				if (!da) return;
				//getId('spSignLastDayText').style.display = '';
				var his = getId('tblHis');
				his.innerHTML = '';

				if (!da.sumDetail || !da.sumDetail.length) return;
				for (var i = 0; i < da.sumDetail.length; i++) {
					var s = da.sumDetail[i];
					var tr = document.createElement('tr');
					var td = document.createElement('td');
					td.innerText = s.SignTime;
					tr.appendChild(td);
					td = document.createElement('td');
					td.innerText = s.IP;
					tr.appendChild(td);
					td = document.createElement('td');
					if (s.Platform) {
						td.innerText = 'PC';
						if (s.Platform.indexOf('an') == 0)
							td.innerText = 'Android';
						else if (s.Platform.indexOf('i') == 0)
							td.innerText = 'iOS';
					}
					tr.appendChild(td);
					his.appendChild(tr);
				}
			},
		}
	}
</script>

<style>
	li {
		list-style: none
	}

	#divmain {
		background-color: #4D56A3;
		text-align: center;
		height: 100%;
	}

	/* 	div {
		width: 100%;
	} */

	.clear {
		clear: both
	}

	.clear:after {
		clear: both;
		display: table;
		content: ''
	}

	.sign-layer {
		position: fixed;
		top: 0;
		bottom: 0;
		left: 0;
		z-index: 888;
		display: none;
		width: 100%;
		overflow: auto;
		height: 100%;
	}

	.darkcolor {
		color: #b25d06 !important;
	}

	.darkbcolor {
		background-color: #b25d06 !important;
	}

	.trh {}

	.trh th {
		width: 14.2857%;
		font-size: 140%;
		text-align: center;
		line-height: 60px;
	}

	.trb {
		font-size: 200%;
		font-weight: bold;
	}

	.trb td {
		width: 14.2857%;
		height: calc(width);
		min-height: 50px;
		line-height: 200%;
		text-align: center;
	}

	.trb td div {
		border-radius: 5px;
		background-color: #FFFFF1;
		height: 100%;
		vertical-align: middle;
		position: relative;
	}

	.radius5 {
		border-radius: 5px;
		-webkit-border-radius: 5px;
		-moz-border-radius: 5px;
		-o-border-radius: 5px;
		-ms-border-radius: 5px;
	}

	.sign-cand {
		background-color: #FFBD66;
		padding-bottom: 10px;
		border-radius: 10px;
		max-width: 660px;
		margin: 0 auto;
	}

	.sign-cand * {
		user-select: none;
	}

	.sign-blank {}

	.sign-signed {}

	.sign-unsign {}

	.sign-today {
		background-color: #FFEF7E !important;
	}

	.btns {
		font-size: 150%;
		padding: 4px 10px;
		cursor: pointer;
	}

	.sign-pin {
		position: absolute !important;
		left: 0;
		top: 0;
		margin: 0;
	}

	.svg-triangle {
		width: 35px !important;
		height: 35px !important;
		margin: 0px auto;
	}

	.svg-triangle polygon {
		fill: #7ac143;
		stroke: #65b81d;
		stroke-width: 2;
	}

	#spCurrentDay {
		font-size: 120%;
		line-height: 40px;
		padding-left: 10px;
	}

	.circle {
		width: 6.25rem;
		height: 6.25rem;
		background-color: #FFEB42;
		border-radius: 50%;
		-moz-border-radius: 50%;
		-webkit-border-radius: 50%;
		margin: 0 auto;
	}

	.circle-active {
		box-shadow: 3px 3px 2px #E0A300;
	}

	.smallClose {
		color: grey;
		font-size: 140%;
		float: right;
		margin-right: 10px;
		cursor: pointer;
	}

	.sign-history-body {
		width: 100%;
		height: 100%;
		text-align: center;
		vertical-align: middle;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: rgba(0, 0, 0, .33);
	}

	.sign-history-bodymain {
		border: 3px #33b23f solid;
		border-radius: 5px;
		background-color: #fff;
		opacity: 1;
		height: 60%;
		overflow: auto;
		max-width: 40.625rem;
	}

	.sign-history-head {
		margin-top: 1.5625rem;
		color: #666;
		text-align: center;
		font-size: 0.875rem
	}

	.sign-history-head li {
		float: left;
		width: 33.33%
	}

	.sign-history-head li h4 {
		color: #33b23f;
		font-size: 2.5rem;
		line-height: 3.125rem
	}

	.sign-history-table {
		overflow: auto;
		border-radius: 0.3125rem 0.3125rem 0 0;
	}

	.sign-history-table table {
		width: 100%;
		color: #666;
		text-align: center;
		font-size: 1pc;
		border-spacing: 0
	}

	.sign-history-table table th {
		width: 33.3%;
		background-color: #f2f2f2;
		text-align: center;
		line-height: 40px
	}

	.sign-history-table td {
		width: 33.3%;
		border-bottom: 1px #e5e5e5 dashed;
		line-height: 2.125rem
	}
</style>
